const minimist = require("minimist");
const fs = require("fs");
const path = require("path");
const tar = require("tar");
const Ftp = require("ftp");
const { execSync } = require("child_process");

async function main() {
    const OS_ARCH = "noarch";
    const { BUILD_NUMBER = "" } = process.env;

    const cwd = path.resolve(__dirname, "..");
    const branch = execSync("git rev-parse --abbrev-ref HEAD", { cwd, encoding: "utf8" }).trim();
    const version = execSync("git rev-parse --short HEAD", { cwd, encoding: "utf8" }).trim();

    const suffix = `${OS_ARCH}-${version}@${branch}${BUILD_NUMBER && `-${BUILD_NUMBER}`}`;

    const filename = `ShareWebClient-${suffix}.tar.gz`;

    const archiveFile = path.resolve(cwd, filename);
    const ftpPath = `Module/ShareWebClient/${branch}`;

    await tar.create(
        {
            gzip: true,
            file: archiveFile,
            preservePaths: true,
            cwd,
            prefix: `ShareWebClient-${suffix}/app/ShareWebClient`,
        },
        ["build", "package.json"]
    );

    const { host, user, password } = minimist(process.argv.slice(2));

    if (host && user) {
        const client = new Ftp();

        const mkdir = (name, recursive = true) => {
            return new Promise((resolve, reject) => {
                client.mkdir(name, recursive, (err) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(err);
                    }
                });
            });
        };

        const put = (input, dest) => {
            return new Promise((resolve, reject) => {
                client.put(input, dest, (err) => {
                    if (err) {
                        reject(err);
                    }
                    resolve();
                });
            });
        };

        client.on("ready", async () => {
            console.log(`Upload to FTP: ${host} \n`);
            try {
                await mkdir(ftpPath);

                await put(archiveFile, `${ftpPath}/${filename}`);
                console.log(`${ftpPath}/${filename} 上传成功`);

                await put(archiveFile, `${ftpPath}/ShareWebClient-${OS_ARCH}@${branch}-LATEST.tar.gz`);
                console.log(`${ftpPath}/ShareWebClient-${OS_ARCH}@${branch}-LATEST.tar.gz 上传成功`);

                fs.unlinkSync(archiveFile);
            } catch (err) {
                console.log(err);
                console.log(`${ftpPath}/${filename} 上传失败`);
            }

            client.end();
        });

        client.connect({ host, user, password });
    }
}

main();
